from django.contrib.auth import authenticate
from rest_framework import serializers

from .models import User

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        print(f"Validating user: {username}, password: {password}")

        if username and password:
            user = authenticate(username=username, password=password)

            print(f"Validating user: {user} ")

            # user_obj = User.objects.get(username=username)

            if User.objects.filter(username=username, password=password).exists():
                user_obj = User.objects.get(username=username, password=password)
                print('user_obj================ status:', user_obj.status)
                if user_obj.status:
                    data['user'] = user_obj
                else:
                    raise serializers.ValidationError("用户账户已禁用！")
                # if user_obj.password == password:
                #     data['user'] = user_obj
                #     print("Manual password check passed")  # 调试输出
                # else:
                #     raise serializers.ValidationError("用户名或密码错误")
                #     print("Manual password check failed")  # 调试输出
            else:
                print("User object not found")
                raise serializers.ValidationError("用户名或密码错误！")

            # if user:
            #     if user.is_active:
            #         data['user'] = user
            #     else:
            #         raise serializers.ValidationError("用户账户已禁用！")
            # else:
            #     raise serializers.ValidationError("用户名或密码错误！")
        else:
            raise serializers.ValidationError("必须提供用户名和密码!")

        return data
